<?php

namespace App\Models\User;

use App\Wen\Utils\Utils;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

class WxUserInviteTempCode extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_user_invite_temp_code';


    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if(!_empty_($model->user_id)){
                $model->status = 1;
            }
        });

        static::created(function ($model) {
            // 在模型创建之前触发的操作
            $scene = 'from_user=itc'.$model->id;

            if($model->tenant_id !== null && $model->tenant_id >= 0){
                if(!_empty_($scene)){
                    $scene .= '&';
                }
                $scene .= 'tenant='.$model->tenant_id;
            }
            if(!_empty_($model->scene) && strlen($scene) < 32){
                if(!_empty_($scene)){
                    $scene .= '&';
                }
                $scene .= $model->scene;
            }
            $code = Utils::getMiniCode(_empty_default_($model->path, '/pages/tabbar/index/index') , $scene, 0, 430, false, null, true);
            WxUserInviteTempCode::where('id', $model->id)->update(['code' => $code]);
        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
            if(!_empty_($model->user_id)){
                $model->status = 1;
            }
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'user_id'){

                }
            }
        });
        static::deleted(function ($model) {

        });
        // 其他的模型事件监听...
    }


    public function ower()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }

}
